package com.zscat.mallplus.controller.order;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.controller.single.ApiBaseAction;
import com.zscat.mallplus.oms.entity.OmsOrder;
import com.zscat.mallplus.service.oms.service.IOmsOrderService;
import com.zscat.mallplus.util.PayDigestUtil;
import com.zscat.mallplus.util.PayUtil;
import com.zscat.mallplus.util.ResponseObject;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Auther: shenzhuan
 * @Date: 2019/4/2 15:02
 * @Description:  订单支付
 */
@Slf4j
@RestController
@Api(tags = "OmsController", description = "订单管理系统")
@RequestMapping("/api/orderPayV1")
public class OrderPayController extends ApiBaseAction {

    @Resource
    private IOmsOrderService orderService;

    /**
     * 支付异步结果通知，我们在请求预支付订单时传入的地址
     */
    @IgnoreAuth
    @RequestMapping(value = "/payNotify", method = RequestMethod.POST)
    @ResponseBody
    public String payNotify(HttpServletRequest request) {
        try {
            String payOrderId = request.getParameter("payOrderId");
            if (payOrderId == null) {
                log.info("下单失败");
                return "fail";
            }
            String param1 = request.getParameter("param1");
            if (param1 == null) {
                log.info("下单失败");
                return "fail";
            }
            // 校验充值的签名
            Map<String, Object> params = new HashMap<>(10);
            Map<String, String[]> requestParams = request.getParameterMap();

            Iterator<String> iter;
            for (iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = iter.next();
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                params.put(name, valueStr);
            }
            // 验签
            String checkSign = PayDigestUtil.getSign(params, PayUtil.reqKey, "sign");
            String retSign = (String) params.get("sign");
            if (!checkSign.equals(retSign)) {
                System.out.println("=========验签失败=========");
                System.out.println("支付失败");
                return "fail";
            }
            JSONObject param1Result = JSON.parseObject(param1);
            // 第三方支付
            Boolean isSuccess = param1Result.getBoolean("isSuccess");
            // 查询结果是否支付成功
            if (isSuccess) {
                OmsOrder orderInfo = new OmsOrder();
                orderInfo.setTotalOrderSn(payOrderId);// 总订单号
                orderInfo.setStatus(2);               // 已支付
                orderInfo.setConfirmStatus(1);       // 已支付
                orderInfo.setPaymentTime(new Date());
                orderService.updateById(orderInfo);
                // 支付成功
                System.out.println("支付成功");
                ResponseObject reObj = new ResponseObject();
                reObj.setCode(0);
                reObj.setMsg("success");
                return "success";
            } else {
                // 支付失败
                System.out.println("支付失败");
                return "fail";
            }
        } catch (Exception e) {
            System.out.println("支付失败:" + e.getMessage());
            return "fail";
        }
    }
}
